package org.ccay.excel.importer.service.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;
import javax.inject.Named;

import org.ccay.async.AsyncMessage;
import org.ccay.async.IMessageSender;
import org.ccay.async.task.ImportTaskVO;
import org.ccay.async.task.service.IImportTaskService;
//import org.ccay.core.annotation.CcayOperation;
//import org.ccay.core.annotation.CcayResource;
//import org.ccay.core.annotation.NoCcayTransation;
//import org.ccay.core.annotation.SecurityPolicy;
import org.ccay.core.exception.ApplicationException;
import org.ccay.core.log.ILogger;
import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.request.impl.RequestContext;
import org.ccay.core.util.AssertUtil;
import org.ccay.core.util.JsonUtil;
import org.ccay.core.util.StringUtil;
import org.ccay.excel.importer.ExcelImportRequest;
import org.ccay.excel.importer.service.IExcelImportService;
//import org.ccay.security.AuthorizationException;

/**
 * 支持重新导入Excel任务
 * 
 * @author chaowangbang
 * @since: 2015年6月15日
 * @version: V5R04 SP15
 */
@Named
//@CcayResource(code = "Excel.Import", desc = "Ccay Excel Import Management")
public class ExcelImportService implements IExcelImportService {
	
	private static final ILogger logger = CcayLoggerFactory.getLogger(ExcelImportService.class);
	
	@Inject
	private IImportTaskService importTaskService;
	
	@Inject 
	private IMessageSender messageSender;

//	@NoCcayTransation
//	@CcayOperation(policy=SecurityPolicy.AllSystemUser)
	public ImportTaskVO doImportTask(Integer taskId) throws ApplicationException {
		// 导入任务ID不能为空
		AssertUtil.assertObjectNotNull(taskId, "taskId");
		// 根据ID查询导入任务，如果找不到任务会抛异常
		ImportTaskVO importTask =  importTaskService.findImportTaskById(taskId);
		// 权限验证，只能导入自己上传的EXCEL文件
		long createUser = importTask.getCreatedBy();
		long currentUser = importTask.getCurrentUserId();
		if (createUser != currentUser) {
			// TODO throw new AuthorizationException();
		}
		// 获取excelType
		String excelType = importTask.getTaskType();
		if(StringUtil.isNullOrEmpty(excelType)){
			String typeId = importTask.getTypeId();
			excelType = importTask.getAppName() + "." + StringUtil.firstLowerCase(typeId);
		}
		// 获取请求参数
		String taskParameters = importTask.getParameters();
		Map<String, String> parameters = new HashMap<String, String>();
		if(!StringUtil.isNullOrEmpty(taskParameters)){
			try {
				parameters = (Map<String, String>)JsonUtil.stringToObject(taskParameters, Map.class);
			} catch (IOException e) {
				logger.error("Fail to convert task({0}) param : {1}", taskId, taskParameters);
				logger.error(e);
			}
		}else {
			logger.warn("Import parameters is lost for task : {0}", taskId);
		}
		// 构造excel导入请求
		ExcelImportRequest importRequest = new ExcelImportRequest(excelType);
		importRequest.setTaskId(taskId);
		importRequest.setDisplayFileName(importTask.getDisplayFileName());
		importRequest.setParameters(parameters);
		importRequest.setUserLanguage(RequestContext.getCurrent().getUserLanguage());
		
		// 发送异步消息
		AsyncMessage message = new AsyncMessage("ExcelImport");
		message.setContent(importRequest);
		messageSender.send(message);	
		
		return importTask;
	}
}
